package com.inspur.controller;

import com.inspur.common.ResultCode;
import com.inspur.common.ServerResponse;
import com.inspur.common.StringTools;
import com.inspur.pojo.UserAccount;
import com.inspur.pojo.UserInfo;
import com.inspur.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@Controller
public class UserController {
    public static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private IUserService iUserService;

    @RequestMapping("/toLogin")
    public String login(String userName, String password,HttpSession session){
        if(LOGGER.isDebugEnabled()){
            LOGGER.debug(" enter UserController.login, userName:{},password:{}",userName,password);
        }
        if(StringTools.isEmpty(userName)){
            session.setAttribute("result",ResultCode.USERNAME_IS_EMPTY.getDesc());
            LOGGER.error("error UserController.login userName is Empty;");
            return "login";
        }
        if(StringTools.isEmpty(password)){
            session.setAttribute("result",ResultCode.PASSWORD_IS_EMPTY.getDesc());
            LOGGER.error("error UserController.login password is Empty;");
            return "login";
        }
        ServerResponse response = iUserService.login(userName,password);
        if(response.isSuccess()){
            UserAccount userAccount = (UserAccount) response.getData();
            session.setAttribute("roleName",userAccount.getRoleName());
            ServerResponse serverResponse = iUserService.getUserInfoByUserName(userAccount.getUserName());
            session.setAttribute("userInfo",serverResponse.getData());
            if(LOGGER.isDebugEnabled()){
                LOGGER.debug("exit UserController.login ,ServerResponse:{}",response);
            }
            return "index";
        }else{
            session.setAttribute("result",response.getData());
            if(LOGGER.isDebugEnabled()){
                LOGGER.debug("exit UserController.login ,ServerResponse:{}",response);
            }
            return "login";
        }
    }

    /**
     * 注册账户
     * @param request
     * @param userInfo
     * @param userAccount
     * @param uploadImage
     * @return
     */
    @RequestMapping("/register")
    public String register(HttpServletRequest request, UserInfo userInfo, UserAccount userAccount, @RequestParam("uploadImage")MultipartFile uploadImage){
        if(LOGGER.isDebugEnabled()){
            LOGGER.debug(" enter UserController.login, userInfo:{},userAccount:{}",userInfo,userAccount);
        }
        // 头像文件名称
        String fileName = uploadImage.getOriginalFilename();
        // 用户账号
        String userName = userAccount.getUserName();
        String userImageName = userName+fileName.substring(fileName.indexOf("."),fileName.length());
        String path = request.getServletContext().getRealPath("/userHead/");

        userInfo.setUserPhoto("/userHead/"+userImageName);
        ServerResponse response = upLoadFile(request,uploadImage,userImageName,path+userImageName);
        ServerResponse rep =null;
        if(response.isSuccess()){
            rep = iUserService.register(userAccount,userInfo);
            if(rep.isSuccess()){
                return "login";
            }
        }else{
            rep= ServerResponse.getResponseFailByDesc("头像上传失败");
        }
        if(LOGGER.isDebugEnabled()){
            LOGGER.debug("exit UserController.login ,ServerResponse:{}",rep);
        }
        return  "login";
    }

    /**
     * 上传文件
     * @param request
     * @param file
     * @param fileName
     * @return
     */
    @RequestMapping("/upLoadFile")
    @ResponseBody
    public ServerResponse upLoadFile(HttpServletRequest request,@RequestParam("testImg")MultipartFile file,String fileName,String path){
        if(file!=null){
            System.out.println("path = " + path);
            File filepath = new File(path,fileName);
            //判断路径是否存在，如果不存在就创建一个
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            //将上传文件保存到一个目标文件当中
            try {
                file.transferTo(new File(path + File.separator + fileName));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ServerResponse.getSuccess();
        }else{
            System.out.println("null");
        }
        return ServerResponse.getResponseFail(ResultCode.OTHER_ERROR);

    }
    @RequestMapping("/test")
    public String test(){
        return "test";
    }
}
